package com.android.uu.view;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.EditText;

/**可以设定小数点后几位的数字输入EdtiText
 * @author GuiyouZhang
 * Date：2015年10月18日 下午4:22:02
 * Email:guiyouzhang@163.com
 */
public class NumberSignedEditText extends EditText {

	private Context mContext;
	private int length = 0;// 输入小数点后几位

	public NumberSignedEditText(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	public NumberSignedEditText(Context context, AttributeSet attrs,
			int defStyle) {
		super(context, attrs, defStyle);
		mContext = context;
		init();
	}

	public NumberSignedEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		init();
	}
	
	public void setLengthAfterDot(int length) {
		this.length = length;
	}

	private void init() {
		addTextChangedListener(new TextWatcher() {
			private boolean isChanged = false;

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if (isChanged) {// ----->如果字符未改变则返回
					return;
				}
				String str = s.toString();

				isChanged = true;
				String cuttedStr = str;
				/* 删除字符串中的dot */
				for (int i = str.length() - 1; i >= 0; i--) {
					char c = str.charAt(i);
					if ('.' == c) {
						cuttedStr = str.substring(0, i) + str.substring(i + 1);
						break;
					}
				}
				/* 删除前面多余的0 */
				int NUM = cuttedStr.length();
				int zeroIndex = -1;
				for (int i = 0; i < NUM - length; i++) {//这里保证小数点后length位
					char c = cuttedStr.charAt(i);
					if (c != '0') {
						zeroIndex = i;
						break;
					} else if (i == NUM - length - 1) {
						zeroIndex = i;
						break;
					}
				}
				if (zeroIndex != -1) {
					cuttedStr = cuttedStr.substring(zeroIndex);
				}
				/* 如果整数部分为空则补0 */
				if (cuttedStr.length() < length+1) {
					cuttedStr = "0" + cuttedStr;
				}
				/* 加上dot，以显示小数点后两位 */
				cuttedStr = cuttedStr.substring(0, cuttedStr.length() - 2)
						+ "." + cuttedStr.substring(cuttedStr.length() - 2);

				NumberSignedEditText.this.setText(cuttedStr);
				//设置光标到最后
				NumberSignedEditText.this.setSelection(NumberSignedEditText.this.length());
				isChanged = false;
			}
		});
	}
}
